package jjn.round2;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author Jiang Jining
 * @since 2023-05-03 12:06
 */
public class LeetCode1003_CheckIfWordIsValidAfterSubstitutions {
    public boolean isValid(String s) {
        Deque<Character> queue = new LinkedList<>();
        for (char c : s.toCharArray()) {
            if (c == 'a' || c == 'b') {
                queue.offer(c);
                continue;
            }
            if (c == 'c') {
                if (queue.isEmpty()) {
                    return false;
                }
                Character polled = queue.pollLast();
                if (polled != 'b') {
                    return false;
                }
                if (queue.isEmpty()) {
                    return false;
                }
                Character poll = queue.pollLast();
                if (poll != 'a') {
                    return false;
                }
            }
        }
        return queue.isEmpty();
    }
}
